package com.tjetc.utils;

import java.io.FileInputStream;
import java.sql.*;
import java.util.Objects;
import java.util.Properties;

/**
 * jdbc工具类
 */
public final class JdbcUtil1 {
    private static final String USERNAME;
    private static final String PASSWORD;
    private static final String URL;

    private JdbcUtil1(){
        // 可能会发生
        throw new RuntimeException();
    }
    // 目的就是为了将配置文件加载进来，并获取properties对象
    static {
        try {
            Properties properties = new Properties();
            // 加载配置文件
            properties.load(new FileInputStream("/Users/gaoyongxiang/百度网盘/IDEA-Java/202507-java-se/chapter21/src/main/resources/jdbc.properties"));
            USERNAME = properties.getProperty("jdbc.username");
            PASSWORD = properties.getProperty("jdbc.password");
            URL= properties.getProperty("jdbc.url");
        } catch (Exception e) {
            // 这种写法是编译异常转换成运行时异常
            throw new RuntimeException(e);
        }


    }

    /**
     * 获取数据库连接对象
     * @return 数据库连接对象
     */
    public static Connection getConnection(){
        Connection connect;
        try {
            connect = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return connect;
    }

    /**
     * 关闭连接的相关资源
     * @param resultSet 结果集对象
     * @param statement 执行sql语句的对象
     * @param connection 连接数据库的对象
     */
    public static void close(ResultSet resultSet, Statement statement, Connection connection){

        try {
            // 判断是否打开连接
            if (Objects.nonNull(resultSet)) {
                resultSet.close();
            }
            if (Objects.nonNull(statement)) {
                statement.close();
            }
            if (Objects.nonNull(connection)) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
